<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorRecord;
use app\common\model\BehaviorRecordDetail;
use app\common\model\BehaviorRecordImage;
use app\common\model\Student;
use think\Db;
use think\Exception;

/**
 * 班级
 *
 * @package app\api\controller
 */
class Classes extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['students', 'profile', 'behaviorRecords'];

    protected $behaviorCategoryType = [BehaviorCategory::CLASSES];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (学生列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/15)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/classes/students)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="班级ID", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1579073877",
    "data": [
    {
    "id": 2369,
    "number": "20191008",
    "card_number": "55AA2254645644",
    "name": "薛凯琦",
    "pinyin": "wangxiaoer",
    "gender": 0,
    "birthday": "2005-03-12",
    "school_id": 36,
    "grade_id": 1,
    "class_id": 52,
    "created_at": 1574066510,
    "gender_text": "Female"
    }
    ]
    })
     */
    public function students()
    {
        $id = $this->request->request('id', 0);
        $keywords = $this->request->request('keywords', '');

        if (!$id) {
            $this->error('id 不能为空');
        }

        $list = Student::where('class_id', $id)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name|number', 'like', "%$keywords%");
                }
            })
            ->where('status', Student::DISPLAY)
            ->field('id,number,card_number,name,pinyin,gender,avatar,birthday,school_id,grade_id,class_id,created_at')
            ->select();

        if ($list) {
            foreach ($list as $key => $datum) {
                if (!strstr($datum['avatar'], 'http') && strstr($datum['avatar'], '/uploads/')) {
                    $list[$key]['avatar'] = config('mp.url') . $datum['avatar'];
                }
            }
        }
        $this->success('', $list);
    }

    /**
     * @ApiTitle    (班级信息)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/6)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/classes/profile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="班级 ID", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1580971261",
    "data": {
    "id": 52,
    "name": "1班",
    "logo": "http://mp.uxuj.test/assets/images/class_default_logo.png",
    "slogan": null,
    "grade_id": 1,
    "grade_name": "一年级",
    "school_id": 36,
    "school_name": "房山长阳第一小学",
    "school_logo": "http://mp.uxuj.test/uploads/20191118/b4037c02a840db9dd1a78fa6ca932e1e.jpg",
    "classroom_id": 30,
    "classroom_name": "1001教室",
    "building_id": 21,
    "building_name": "逸夫楼",
    "garden_id": 9,
    "garden_name": "本校区",
    "headmaster": 42,
    "headmaster_name": "test",
    "headmaster_avatar": "http://mp.uxuj.test/uploads/20200109/2863d0a1ff4b87ba621cb84637c3796d.jpg",
    "city_name": "北京",
    "positive_score": 0,
    "negative_score": 0
    }
    })
     */
    public function profile()
    {
        $id = $this->request->request('id', 0);

        $ret['data'] = \app\common\model\Classes::alias('classes')
            ->join('__SCHOOL__ school', 'school.id = classes.school_id')
            ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
            ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
            ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
            ->join('__GARDEN__ garden', 'garden.id = building.garden_id', 'left')
            ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->field('classes.id,classes.name,classes.logo,classes.slogan,classes.grade_id,grade.name grade_name,classes.school_id,school.name school_name,school.logo school_logo,classes.classroom_id,classroom.name classroom_name,building.id building_id,building.name building_name,garden.id garden_id,garden.name garden_name,classes.headmaster,user.nickname headmaster_name,user.avatar headmaster_avatar')
            ->where('classes.id', $id)
            ->find();
        if ($ret['data']) {
            if (!strstr($ret['data']->school_logo, 'http') && strstr($ret['data']->school_logo, '/uploads/')) {
                $ret['data']->school_logo = config('mp.url') . $ret['data']->school_logo;
            }
            if (!strstr($ret['data']->headmaster_avatar, 'http') && strstr($ret['data']->headmaster_avatar, '/uploads/')) {
                $ret['data']->headmaster_avatar = config('mp.url') . $ret['data']->headmaster_avatar;
            }
            if (!strstr($ret['data']->logo, 'http') && strstr($ret['data']->logo, '/uploads/')) {
                $ret['data']->logo = config('mp.url') . $ret['data']->logo;
            }
        }

        $records = BehaviorRecord::alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
            ->where('record.class_id', $id)
            ->where('detail.behavior_category_type', BehaviorCategory::CLASSES)
            ->field('SUM(CASE WHEN detail.behavior_type = 1 THEN detail.score ELSE 0 END) positive_score,ABS(SUM(CASE WHEN detail.behavior_type = 2 THEN detail.score ELSE 0 END)) negative_score')
            ->order('score', 'desc')
            ->find();

        $ret['data']['positive_score'] = $records->positive_score ? $records->positive_score : 0;//积极分
        $ret['data']['negative_score'] = $records->negative_score ? $records->negative_score : 0;//消积分

        $this->success('', $ret['data']);
    }

    /**
     * @ApiTitle    (行为列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/17)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/classes/behaviors)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="record_id", type="int", required=false, description="记录id 修改的时候必填", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function behaviors()
    {
        $record_id = $this->request->request(('record_id'));
        $data = BehaviorCategory::getBehaviorData($this->behaviorCategoryType, $record_id, $this->auth->id, $this->auth->school_id);
        $this->success('', $data);
    }

    /**
     * @ApiTitle    (评价)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/6)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/classes/addBehaviorRecord)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="record_id", type="int", required=false, description="记录id 修改的时候必填", sample="")
     * @ApiParams   (name="id", type="int", required=true, description="班级 id", sample="")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|lastweek=上周 5|day7=近7天 6|month=本月 7|lastmonth=上月 8|day30=近30天 9|quarter=本季度 10|lastquarter=上季度 11|year=本年 12|lastyear=上年 13|month1=近一个月 14|month3=近三个月", sample="")
     * @ApiParams   (name="comment", type="string", required=false, description="文字说明", sample="")
     * @ApiParams   (name="images", type="string", required=false, description="图片 以英文 , 分割", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function addBehaviorRecord()
    {
        $record_id = $this->request->request('record_id');
        $id = $this->request->request('id');
        $behavior_data = $this->request->post('behavior_data', [], 'strip_tags');

        $behaviorRecord = [];
        if ($record_id) {
            $behaviorRecord = BehaviorRecord::where('id', $record_id)->find();
            if (!$behaviorRecord) {
                $this->error('记录不存在');
            }
        }

        if ($behavior_data) {
            $behavior_data = json_decode($behavior_data, true);
            if (!$behavior_data || !is_array($behavior_data)) {
                $this->error('参数错误');
            }
        } else {
            $this->error('参数错误');
        }

        // 筛选出所有要点评的行为 id
        $behavior_ids = array_column($behavior_data, 'behavior_id');
        if (!$behavior_ids) {
            $this->error('参数错误');
        }

        // 获取行为信息
        $behaviors = \app\common\model\Behavior::alias('behavior')
            ->join('__BEHAVIOR_CATEGORY__ category', 'category.id = behavior.category_id')
            ->join('__BEHAVIOR_IMAGE__ image', 'image.id = behavior.image_id', 'left')
            ->whereIn('behavior.id', $behavior_ids)
            ->whereIn('category.type', $this->behaviorCategoryType)
            ->column('behavior.*,category.name category_name,category.type category_type,category.is_deduct,image.url image_url', 'behavior.id');
        if (!$behaviors) {
            $this->error('您选择的行为不存在');
        }

        //获取班级信息
        $classes = \app\common\model\Classes::alias('classes')
            ->join('__SCHOOL__ school', 'school.id = classes.school_id')
            ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
            ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
            ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
            ->join('__GARDEN__ garden', 'garden.id = building.garden_id', 'left')
            ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
            ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
            ->field('classes.id,classes.name,classes.logo,classes.slogan,classes.grade_id,grade.name grade_name,classes.school_id,school.name school_name,school.logo school_logo,classes.classroom_id,classroom.name classroom_name,building.id building_id,building.name building_name,garden.id garden_id,garden.name garden_name,classes.headmaster,user.nickname headmaster_name,user.avatar headmaster_avatar')
            ->where('classes.id', $id)
            ->find();

        if (!$classes) {
            $this->error('班级不存在');
        }

        // 当前用户信息
        $user = $this->auth->getUserinfo();

        Db::startTrans();
        try {

            if ($behaviorRecord) {
                db('behavior_record_detail')->where('record_id', $behaviorRecord->id)->delete();
                db('behavior_record_image')->where('record_id', $behaviorRecord->id)->delete();
            } else {
                $behaviorRecord = new BehaviorRecord();
                $behaviorRecord->save([
                    'record_user_id' => $user['id'],
                    'record_username' => $user['nickname'],
                    'record_user_group' => $user['group_name'],
                    'behavior_category_type' => BehaviorCategory::CLASSES,
                    'school_id' => $classes['school_id'],
                    'class_id' => $classes['id'],
                    'teacher_id' => $classes['headmaster'],
                    'json_data' => json_encode([
                        'school_id' => $classes['school_id'],
                        'school_name' => $classes['school_name'],
                        'grade_id' => $classes['grade_id'],
                        'grade_name' => $classes['grade_name'],
                        'class_id' => $classes['id'],
                        'class_name' => $classes['name'],
                        'classroom_id' => $classes['classroom_id'],
                        'classroom_name' => $classes['classroom_name'],
                        'headmaster_id' => $classes['headmaster'],
                        'headmaster_name' => $classes['headmaster_name'],
                    ])
                ]);
            }

            $behaviorRecordDetail = new BehaviorRecordDetail();
            $detail_insert_data = [];
            foreach ($behavior_data as $key => $value) {
                if (isset($behaviors[$value['behavior_id']])) {
                    $behavior = $behaviors[$value['behavior_id']];
                    $detail_insert_data[] = [
                        'record_id' => $behaviorRecord->id,
                        'behavior_category_id' => $behavior['category_id'],
                        'behavior_category_type' => $behavior['category_type'],
                        'behavior_id' => $behavior['id'],
                        'behavior_name' => $behavior['name'],
                        'behavior_type' => $behavior['type'],
                        'behavior_image_id' => $behavior['image_id'],
                        'behavior_image_url' => $behavior['image_url'],
                        'unit_score' => $behavior['type'] == 1 ? $behavior['score'] : $behavior['score'] * (-1),
                        'count' => $value['count'],
                        'score' => $behavior['type'] == 1 ? $value['count'] * $behavior['score'] : $value['count'] * $behavior['score'] * (-1),
                        'is_deduct' => $behavior['is_deduct'],
                        'comment' => @$value['comment'],
                        'class_id' => $classes['id'],
                    ];
                }
            }
            if ($detail_insert_data) {
                $details = $behaviorRecordDetail->saveAll($detail_insert_data);
                $behavior_images = array_column($behavior_data, 'images', 'behavior_id');

                $image_insert_data = [];
                foreach ($details as $key => $value) {
                    if (isset($behavior_images[$value->behavior_id])) {
                        if (!is_array($behavior_images[$value->behavior_id])) {
                            $behavior_images[$value->behavior_id] = explode(',', $behavior_images[$value->behavior_id]);
                        }
                        foreach ($behavior_images[$value->behavior_id] as $k => $v) {
                            $image_insert_data[] = [
                                'record_id' => $behaviorRecord->id,
                                'record_detail_id' => $value->id,
                                'url' => $v,
                            ];
                        }
                    }
                }

                if ($image_insert_data) {
                    $behaviorRecordImage = new BehaviorRecordImage();
                    $behaviorRecordImage->saveAll($image_insert_data);
                }
            } else {
                Db::rollback();
                $this->error('点评失败');
            }

            Db::commit();

        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * @ApiTitle    (评价记录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/18)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/student/behaviorRecords)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="学生 id", sample="")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|lastweek=上周 5|day7=近7天 6|month=本月 7|lastmonth=上月 8|day30=近30天 9|quarter=本季度 10|lastquarter=上季度 11|year=本年 12|lastyear=上年 13|month1=近一个月 14|month3=近三个月", sample="")
     * @ApiParams   (name="page", type="int", required=false, description="页码", sample="")
     * @ApiParams   (name="listRows", type="int", required=false, description="每页条数", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function behaviorRecords()
    {
        $id = $this->request->request('id');
        $time_type = $this->request->request('time_type');
        $page = $this->request->request('page', 1);
        $listRows = $this->request->request('listRows');

        if (1 == $page) {
            $charts = BehaviorRecord::getCharts(BehaviorCategory::CLASSES, $id);
            if (isset($charts['error'])) {
                $this->error($charts['msg']);
            }
        }

        $list = BehaviorRecord::getRecords(BehaviorCategory::CLASSES, $id, $this->behaviorCategoryType, $time_type, $listRows);

        if (isset($list['error'])) {
            $this->error($list['msg']);
        }

        $this->success('', compact('charts', 'list'));
    }

}
